package org.example.springbootwebexample.service.impl;


import org.example.springbootwebexample.mapper.DeptMapper;
import org.example.springbootwebexample.mapper.EmpMapper;
import org.example.springbootwebexample.pojo.Dept;
import org.example.springbootwebexample.pojo.DeptLog;
import org.example.springbootwebexample.service.DeptLogService;
import org.example.springbootwebexample.service.DeptService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;


import java.time.LocalDateTime;
import java.util.List;

@Component
public class DeptServiceImpl implements DeptService {


    @Autowired
    private DeptMapper deptMapper;
    @Autowired
    private EmpMapper empMapper;
    @Autowired
    private DeptLogService deptLogService;

    public List<Dept> list(){

        return deptMapper.list();
    }


    /**
     * 解散部门
     * @param id
     */
    @Transactional(rollbackFor = Exception.class)   //spring事务管理的注解 - 出现所有的异常都需要回滚
    public void delete(Integer id){

        try {
            //1.根据id 删除部门
            deptMapper.delete(id);

            //2.根据部门id 删除部门下的员工
            empMapper.deleteByDeptId(id);

        } finally {
            //3.记录解散部门的日志
            DeptLog deptLog = new DeptLog();
            deptLog.setCreateTime(LocalDateTime.now());
            deptLog.setDescription("执行解散部门的操作，部门id :" + id);
            deptLogService.insert(deptLog);
        }


    }

    public void add(Dept dept){
        dept.setCreateTime(LocalDateTime.now());
        dept.setUpdateTime(LocalDateTime.now());
        deptMapper.add(dept);
    }


}
